<template>
  <div class="vulnerability-analysis-result">
    <div class="result-header">
      <h3>供应链脆弱性分析</h3>
      <el-button type="primary" @click="handleExport" plain>
        <el-icon><Download /></el-icon> 导出数据
      </el-button>
    </div>

    <div class="analysis-description">
      <p>本分析结合产品关系数据和企业生产数据，评估产品链中特定材料的供应稳定性，识别可能导致供应链中断的脆弱点。</p>
    </div>

    <!-- 材料供应风险表格 -->
    <div class="risk-table-container">
      <h4>关键材料供应商风险状况</h4>
      <el-table
        v-if="materialData.length > 0"
        :data="materialData"
        border
        style="width: 100%"
        :max-height="maxHeight"
        default-sort="{ prop: 'riskRatio', order: 'descending' }"
      >
        <el-table-column prop="productName" label="材料名称" min-width="150" sortable>
          <template #default="{ row }">
            <el-tooltip
              :content="getProductTooltip(row)"
              placement="top"
              :show-after="500"
            >
              <span class="material-name">{{ row.productName }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <el-table-column prop="producerCount" label="生产企业数" width="120" sortable align="center">
          <template #default="{ row }">
            <el-tag :type="getProducerCountType(row.producerCount)">
              {{ row.producerCount }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="highRiskProducerCount" label="高风险企业数" width="120" sortable align="center">
          <template #default="{ row }">
            {{ row.highRiskProducerCount }}
          </template>
        </el-table-column>
        
        <el-table-column prop="riskRatio" label="风险比例" width="140" sortable align="center">
          <template #default="{ row }">
            <div class="risk-progress">
              <el-progress
                :percentage="Math.round(row.riskRatio * 100)"
                :color="getRiskRatioColor(row.riskRatio)"
                :stroke-width="18"
                :format="(percentage) => percentage + '%'"
              />
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="vulnerabilityLevel" label="脆弱性评级" width="120" sortable align="center">
          <template #default="{ row }">
            <el-tag :type="getVulnerabilityType(row)">
              {{ getVulnerabilityLabel(row) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-else description="暂无数据" />
    </div>

    <!-- 供应脆弱性警告 -->
    <div class="vulnerability-warnings" v-if="hasVulnerabilities">
      <h4>供应链风险警告</h4>
      <el-alert
        v-for="(warning, index) in vulnerabilityWarnings"
        :key="index"
        :title="warning.title"
        :description="warning.description"
        :type="warning.type"
        :closable="false"
        show-icon
        style="margin-bottom: 10px;"
      />
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import { Download } from '@element-plus/icons-vue';
import * as echarts from 'echarts';

export default {
  name: 'SupplyChainVulnerabilityResult',
  components: {
    Download
  },
  props: {
    data: {
      type: Array,
      default: () => []
    },
    maxHeight: {
      type: [String, Number],
      default: '400'
    }
  },
  emits: ['export'],
  setup(props, { emit }) {
    // 转换数据，添加脆弱性评级
    const materialData = computed(() => {
      return (props.data || []).map(item => {
        const riskRatio = parseFloat(item.riskRatio) || 0;
        const producerCount = parseInt(item.producerCount) || 0;
        
        // 评估脆弱性级别
        let vulnerabilityLevel = 'low';
        if (producerCount <= 2 || riskRatio >= 0.5) {
          vulnerabilityLevel = 'high';
        } else if (producerCount <= 5 || riskRatio >= 0.3) {
          vulnerabilityLevel = 'medium';
        }
        
        return {
          ...item,
          riskRatio,
          producerCount,
          highRiskProducerCount: parseInt(item.highRiskProducerCount) || 0,
          vulnerabilityLevel
        };
      });
    });
    
    // 生成警告信息
    const vulnerabilityWarnings = computed(() => {
      const warnings = [];
      
      // 供应商过少的材料
      const lowProducerMaterials = materialData.value.filter(m => m.producerCount <= 2);
      if (lowProducerMaterials.length > 0) {
        warnings.push({
          type: 'error',
          title: '供应商数量过少',
          description: `${lowProducerMaterials.map(m => m.productName).join('、')} 的生产企业少于3家，存在严重的供应链单点故障风险。`
        });
      }
      
      // 高风险比例过高的材料
      const highRiskMaterials = materialData.value.filter(m => m.riskRatio >= 0.5);
      if (highRiskMaterials.length > 0) {
        warnings.push({
          type: 'warning',
          title: '高风险企业比例过高',
          description: `${highRiskMaterials.map(m => m.productName).join('、')} 的生产企业中超过50%存在高风险状况，可能导致供应不稳定。`
        });
      }
      
      return warnings;
    });
    
    const hasVulnerabilities = computed(() => vulnerabilityWarnings.value.length > 0);
    
    // 获取生产企业数量的标签类型
    const getProducerCountType = (count) => {
      if (count <= 2) return 'danger';
      if (count <= 5) return 'warning';
      return 'success';
    };
    
    // 获取风险比例的颜色
    const getRiskRatioColor = (ratio) => {
      if (ratio >= 0.5) return '#F56C6C'; // 红色
      if (ratio >= 0.3) return '#E6A23C'; // 黄色
      return '#67C23A'; // 绿色
    };
    
    // 获取脆弱性评级的标签类型
    const getVulnerabilityType = (row) => {
      switch (row.vulnerabilityLevel) {
        case 'high': return 'danger';
        case 'medium': return 'warning';
        case 'low': return 'success';
        default: return 'info';
      }
    };
    
    // 获取脆弱性评级的显示标签
    const getVulnerabilityLabel = (row) => {
      switch (row.vulnerabilityLevel) {
        case 'high': return '高';
        case 'medium': return '中';
        case 'low': return '低';
        default: return '未知';
      }
    };
    
    // 获取产品的提示信息
    const getProductTooltip = (row) => {
      let tooltip = `生产企业数: ${row.producerCount}`;
      tooltip += `\n高风险企业数: ${row.highRiskProducerCount}`;
      tooltip += `\n风险比例: ${Math.round(row.riskRatio * 100)}%`;
      
      if (row.producerCount <= 2) {
        tooltip += '\n警告: 供应商数量极少，存在供应链单点故障风险';
      }
      
      if (row.riskRatio >= 0.5) {
        tooltip += '\n警告: 高风险企业比例过高，可能导致供应不稳定';
      }
      
      return tooltip;
    };
    
    // 导出数据
    const handleExport = () => {
      emit('export', materialData.value);
    };
    
    return {
      materialData,
      vulnerabilityWarnings,
      hasVulnerabilities,
      getProducerCountType,
      getRiskRatioColor,
      getVulnerabilityType,
      getVulnerabilityLabel,
      getProductTooltip,
      handleExport
    };
  }
};
</script>

<style scoped>
.vulnerability-analysis-result {
  padding: 20px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.result-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.analysis-description {
  margin-bottom: 20px;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

h4 {
  font-size: 16px;
  margin: 20px 0 15px;
  color: #303133;
}

.material-name {
  cursor: help;
  text-decoration: underline dotted;
  text-decoration-thickness: 1px;
  text-underline-offset: 2px;
}

.vulnerability-warnings {
  margin-top: 20px;
}

.risk-progress {
  padding: 0 5px;
}

:deep(.el-table) {
  margin-bottom: 20px;
}

:deep(.el-tag) {
  width: 100%;
  text-align: center;
}

:deep(.el-progress-bar__innerText) {
  font-weight: bold;
}
</style> 